package com.chk.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chk.commom.constants.AppHttpCodeEnum;
import com.chk.commom.utils.BeanCopyUtils;
import com.chk.commom.utils.CodeUtils;
import com.chk.commom.utils.CommonResult;
import com.chk.commom.utils.JwtUtil;
import com.chk.user.entity.User;
import com.chk.user.mapper.UserMapper;
import com.chk.user.service.UserService;
import com.chk.user.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.stream.Collectors;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-10-20 11:00:20
 */
@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public CommonResult login(User user, HttpServletRequest request) {
        //查询 数据库的对象
        String code = user.getCode();
        //验证码
        if(request.getSession(true)
                .getAttribute("code")==null
                ||
                !code.toUpperCase()
                        .equals(request.getSession(true)
                                .getAttribute("code")
                                .toString().toUpperCase())){

            return CommonResult.failed(AppHttpCodeEnum.CODE_ERROR);
        }
        String username = user.getUsername();
        User loginUser = userMapper.getUserByUsername(username);
        //校验密码
        HttpSession session = request.getSession(true);
        //移除session中的验证码
        session.removeAttribute("code");
        if (loginUser != null && passwordEncoder.matches(user.getPassword(), loginUser.getPassword())) {
            //创建token
            String token = JwtUtil.createToken(loginUser);
            return CommonResult.okResult(token);
        }
        return CommonResult.failed(AppHttpCodeEnum.LOGIN_ERROR);
    }

    @Override
    public CommonResult getCode(HttpServletRequest request, HttpServletResponse res) throws IOException {
        CodeUtils code = new CodeUtils();
        BufferedImage image = code.getImage();
        String text = code.getText();
        HttpSession session = request.getSession(true);
        session.setAttribute("code", text);
        System.out.println(text);
//        图片形式
//        CodeUtils.output(image,res.getOutputStream());
//        data:image形式
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);
        byte[] imageBytes = byteArrayOutputStream.toByteArray();

        // 将字节数组转换为Base64编码的字符串
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        // 拼接成data:image格式
        String dataURL = "data:image/jpeg;base64," + base64Image;
        return CommonResult.okResult(dataURL);
    }

    @Override
    public CommonResult getCurrentUserInfo(HttpServletRequest request) {
        User user = new User();
        try {
            user = JwtUtil.parseToken(request.getHeader("token"), User.class);
        }catch (Exception e){
            System.out.println(e);
            return CommonResult.failed(AppHttpCodeEnum.JWT_ERROR);
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,user.getId());
        return CommonResult.okResult(BeanCopyUtils.copyBean(this.getOne(queryWrapper), UserVo.class));
    }

    @Override
    public CommonResult getUserList(String condition, Integer pageNow, Integer pageSize) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(condition)) {
            queryWrapper.like(User::getUsername, condition)
                    .or().like(User::getUserNick, condition)
                    .or().like(User::getEmail, condition)
                    .or().like(User::getPhone, condition)
                    .or().like(User::getAddress, condition);
        }
        queryWrapper.orderByAsc(User::getId);
        //获取列表id
        Page<User> userPage = new Page<>(pageNow, pageSize);
        log.info(userPage.toString());
        Page<User> page = this.page(userPage, queryWrapper);
        // 返回封装成Vo的类
        return CommonResult.okResult(page.getRecords().stream().map(user -> BeanCopyUtils.copyBean(user, UserVo.class)).collect(Collectors.toList()));
    }
}

